package com.impetus.project.skilltest.service;

import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.impetus.project.skilltest.core.SkillTestException;
import com.impetus.project.skilltest.dao.CandidateDAO;
import com.impetus.project.skilltest.dataobject.Candidate;

public class SecurityService {
	
	// List of users/candidates logged in
	private static Logger logger = Logger.getLogger(SecurityService.class.getName());
	
	private static Map<String,Candidate> session = new TreeMap<String, Candidate>();
	
	public static Candidate login(String userid, String password)
	throws SkillTestException
	{
		Candidate candidate = CandidateDAO.getCandidateByUserNamePassword(userid, password);
		if (null != candidate)
		{
			logger.log(Level.INFO, "Adding session entry for " + userid);
			session.put(userid, candidate);
		}
		return candidate;
		
	}
	
	public static void logout(Candidate candidate)
	{
		try{
			if(session.containsKey(candidate))
			{
				String userid = candidate.getCandidateid(); 
				session.remove(userid);
				logger.log(Level.INFO, userid + " logged out ");
			}
		}catch(Exception e)
		{
			logger.log(Level.INFO, "Failed to logout "+ e.getMessage());
		}
	}
	
	public static boolean checkLogin(Candidate candidate)
	throws SkillTestException
	{
		String userid = candidate.getCandidateid();
		if(session.containsKey(userid))
		{
			logger.log(Level.INFO, userid + " is currently logged in ");
			return true;
		}else
		{
			return false;
		}
	}
}
